package service

import (
	"cms/model"
	"crypto/md5"
	"engine/consts"
	"engine/dto"
	emodel "engine/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"lib/character"
	"lib/db"
	"lib/log"
	sferrors "lib/sf-errors"
	"time"
)

func CreateSysUser(req *model.RegisterUserReq) (*emodel.SysUserDetail, error) {
	tuser, err := dto.QuerySysUserByMobile(req.Mobile)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	if tuser != nil && tuser.Id > 0 {
		return nil, sferrors.NewStringf("用户已注册")
	}

	//邀请码
	parentUser, err := dto.QuerySysUserByQrcode(req.InvitationCode)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	if parentUser == nil || parentUser.Id <= 0 {
		return nil, sferrors.NewString("未找到邀请码")
	}
	q := GetUserQ("")
	hashPassword, err := character.GetHashGenerateCRandom(req.Password)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	//
	//if len(req.Pwd) != 6 {
	//	return nil, sferrors.NewString("支付密码错误！")
	//}

	//newPwdStr, err := Md5PayPwd(req.Password)
	//if err != nil {
	//	return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	//}
	sysUser := &emodel.My_user{
		Q:            q,
		Pid:          parentUser.Id,
		Ppid:         parentUser.Pid,
		PasswordHash: hashPassword,
		Password:     hashPassword,
		Nickname:     req.Mobile[:3] + "******" + req.Mobile[7:],
		Mobile:       req.Mobile,
		Status:       string(consts.StatusNormal),
		//Pwd:          newPwdStr,
	}

	err = dto.CreateSysUser(sysUser)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	newUser, err := dto.GetSysUserDetailById(sysUser.Id)
	if err != nil {
		log.Errorf("获取用户信息失败：%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	return newUser, nil
}
func GetPwd(operator *emodel.My_user) (username, password string) {
	return fmt.Sprintf("%d", operator.Id), hash_md5_fun(fmt.Sprintf("%d%s%s", operator.Id, operator.Mobile, operator.Email))
}

func hash_md5_fun(pwd string) string {
	data := []byte(pwd)               // 字符串转byte
	has := md5.Sum(data)              // 对byte数据加密
	md5str1 := fmt.Sprintf("%x", has) // 将[]byte转成16进制
	return md5str1
}

func UpdateSysUser(ctx *gin.Context, req *model.AdminUserUpdateRequest, sysUser *emodel.My_user) (*emodel.SysUserDetail, error) {
	sysUser.Nickname = req.Nickname
	sysUser.Mobile = req.Mobile

	err := dto.UpdateSysUser(ctx, sysUser)
	if err != nil {
		log.Errorf("修改用户信息失败：%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	newUser, err := dto.GetSysUserDetailById(sysUser.Id)
	if err != nil {
		log.Errorf("获取用户信息失败：%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	return newUser, nil
}

func SysUserResetPassword(ctx *gin.Context, user *emodel.SysUserDetail) (*emodel.SysUserDetail, error) {
	password, hashPassword, err := character.GetHashGenerateRandom(10)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	user.PasswordHash = hashPassword
	err = dto.ResetSysUserPassword(ctx, user)
	if err != nil {
		log.Errorf("%v", err)
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	user.Password = password
	return user, nil
}

func GetUserLogsLevel(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_level_now], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_level_now](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
		ShowSQL:  true,
	})
}

func GetUserLogs(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_user_score_log], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()
	if req.Start != "" || req.End != "" {
		_, err := time.Parse("2006-01-02 15:04:05", req.Start)
		if err != nil {
			return nil, sferrors.New(err).SetCode(sferrors.SystemError)
		}
		_, err = time.Parse("2006-01-02 15:04:05", req.End)
		if err != nil {
			return nil, sferrors.New(err).SetCode(sferrors.SystemError)
		}
		query = query.Where("createtime >= ? and createtime<=?", req.Start, req.End)
	}
	if req.Query != "" {
		query = query.Where(
			query.Where("memo like ?", "%"+req.Query+"%"),
		)
	}

	if req.Type == 0 {
		query = query.Where("type=?", 0)
	} else if req.Type == 1 {
		query = query.Where("type=?", 1)
	} else if req.Type == 2 {
		query = query.Where("type=?", 2)
	} else if req.Type == 3 {
		query = query.Where("type=?", 3)
	} else if req.Type == 4 {
		query = query.Where("type=?", 4)
	} else if req.Type == 5 {
		query = query.Where("type=?", 5)
	} else {
		//query = query.Where("type=?", 1)
	}

	query = query.Where("user_id=?", moduleId)
	query = query.Order("id desc")

	return dto.Paginate[emodel.My_user_score_log](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
		ShowSQL:  true,
	})
}

func GetUserLogsNewTow(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_user_score_log], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	return EsUserLogsHistorySelect(req.Type, moduleId, req.Page, req.Indexs)
}

func GetUserUnlock(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_order_w], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	var types = "0"
	if req.Type == 0 {
		types = "4"
	} else if req.Type == 1 {
		types = "0"
	} else if req.Type == 2 {
		types = "1"
	} else if req.Type == 3 {
		types = "2"
	}

	query := db.GetDb().Where("uid=? and status=?", moduleId, types)
	query = query.Order("id desc")
	newList, _ := dto.Paginate[emodel.My_order_w](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
	nowTimestamp := time.Now().Unix()
	if len(newList.Items) > 0 {

		for i, item := range newList.Items {
			s := item.EndTime - nowTimestamp
			if s < 0 {
				s = 0
			}
			newList.Items[i].EndTime = s
			if item.Status == 2 {
				item.Flag = 2
			}
		}
	}

	return newList, nil
}

func GetTzExtract(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_tz_extract], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	var types = "0"
	if req.Type == 0 {
		types = "0"
	} else if req.Type == 1 {
		types = "1"
	} else if req.Type == 2 {
		types = "2"
	} else if req.Type == 3 {
		types = "2"
	}

	query := db.GetDb().Where("uid=? and status=?", moduleId, types)
	query = query.Order("id desc")
	newList, _ := dto.Paginate[emodel.My_tz_extract](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})

	return newList, nil
}

func GetUserLogsNew(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_order_dea], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	if req.Type == 999 {
		query = query.Where("puid=101 and flag=33")
		return dto.Paginate[emodel.My_order_dea](query, &dto.PaginatorOption{
			Page:     req.Page,
			PageSize: 15,
		})
	} else {
		query = query.Where("uid=? or puid=?", moduleId, moduleId)
	}

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_order_dea](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}

func GetUserLogsNewTz(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_order_dea_tz], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	if req.Type == 999 {
		query = query.Where("puid=101 and flag=33")
		return dto.Paginate[emodel.My_order_dea_tz](query, &dto.PaginatorOption{
			Page:     req.Page,
			PageSize: 15,
		})
	} else {
		query = query.Where("uid=? or puid=?", moduleId, moduleId)
	}

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_order_dea_tz](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}
func GetGames(ctx *gin.Context) (*dto.PaginationList[emodel.My_games], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}

	query := db.GetDb().Where("switch=1").Order("id asc")

	return dto.Paginate[emodel.My_games](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}

func GetNewMsgNew(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_msg], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()
	order := "id desc"
	if req.Page > 1 {
		order = "id desc"
	}
	query = query.Order(order)

	return dto.Paginate[emodel.My_msg](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 10,
	})
}
func GetJihuos(ctx *gin.Context, moduleId uint64, types string) (*dto.PaginationList[emodel.My_jihuo], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	query = query.Where("bz=?", moduleId)
	if types == "1" {
		query = query.Where("sy=0")
	}
	if types == "2" {
		query = query.Where("sy=1")
	}

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_jihuo](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}

func GetNoticeLogs(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_notice], error) {
	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_notice](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 10,
		ShowSQL:  true,
	})
}

func HandleTask(pageList *dto.PaginationList[emodel.My_user]) *dto.PaginationList[model.StearmReq] {
	var newData dto.PaginationList[model.StearmReq]
	newList := make([]*model.StearmReq, 0)

	days := time.Now().Format("20060102")
	for _, item := range pageList.Items {
		newList = append(newList, &model.StearmReq{
			Nickname:   item.Mobile[:3] + "******" + item.Mobile[7:11],
			Avatar:     item.Avatar,
			Createtime: item.CreateTime[:10] + " " + item.CreateTime[11:16],
			DyTure:     item.DyTure,
			Level:      item.Level,
			Rw:         dto.GetTaskCount(item.Id, 0),
			TdNum:      dto.GetTaskCount(item.Id, 1),
			ToDayTask:  dto.GetTodayTask(item.Id, days),
			//Z30Num: dto.GetTaskCountGT30(item.Id, 0),
			//J30Num: dto.GetTaskCountGT30(item.Id, 1),
			Id:     item.Id,
			IsTrue: item.IsTask,
			Bio:    item.Bio,
			Beizhu: item.Beizhu,
			WPid:   item.WPid,
			Wppid:  item.WPPid,
			Y:      fmt.Sprintf("%v", item.Y),
		})
	}

	//下级有没有完成任务

	newData.Items = newList
	return &newData
}

func GetJihuosNow(ctx *gin.Context, moduleId uint64, types string) (*dto.PaginationList[emodel.My_online_order], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	if req.OrderType == 0 {
		query = query.Where("uid=? and ch_id=0", moduleId)
	} else if req.OrderType == 1 {
		query = query.Where("uid=? and ch_id>0", moduleId)
	} else if req.OrderType == 2 {
		query = query.Where("ch_id=?", moduleId)
	}

	if types == "1" {
		query = query.Where("status=0")
	}
	if types == "2" {
		query = query.Where("status=1")
	}
	if types == "3" {
		query = query.Where("status=2")
	}
	query = query.Order("id desc")

	return dto.Paginate[emodel.My_online_order](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}

func GetChildNow(ctx *gin.Context, moduleId uint64, types string) (*dto.PaginationList[emodel.My_child_order], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	order := "id desc"
	if req.OrderType == 0 {
		order = "id asc"
		query = query.Where("uid=?", moduleId)
	}

	if types == "1" {
		query = query.Where("status=0")
	}
	if types == "2" {
		query = query.Where("status=1")
	}
	if types == "3" {
		query = query.Where("status=2")
	}
	query = query.Order(order)

	return dto.Paginate[emodel.My_child_order](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}
func GetDuihuanNow(ctx *gin.Context, moduleId uint64) (*dto.PaginationList[emodel.My_jihuo], error) {

	req := model.QueryUserLogRequest{}
	if err := ctx.ShouldBindQuery(&req); err != nil {
		return nil, sferrors.New(err).SetCode(sferrors.SystemError)
	}
	query := db.GetDb()

	if req.Type == 0 {
		query = query.Where("pid=?", moduleId)
	} else if req.Type == 1 {
		query = query.Where("pid=? and uid=0", moduleId)
	} else if req.Type == 2 {
		query = query.Where("pid=? and uid>0", moduleId)
	}

	query = query.Order("id desc")

	return dto.Paginate[emodel.My_jihuo](query, &dto.PaginatorOption{
		Page:     req.Page,
		PageSize: 15,
	})
}
